import { useEffect } from "react";
import { flushSync } from 'react-dom';
import { request, useModel, useNavigate } from '@umijs/max';
import { Footer } from '@/components';
import { Form, message, theme } from 'antd';
import { LoginForm, ProFormCheckbox, ProFormText, } from '@ant-design/pro-components';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { clearCookie, getCookie, setCookie } from '@/utils/rememberPassword';
import { createStyles } from 'antd-style';

const useStyles = createStyles(({ token }) => {
  return {
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

export default () => {
  let navigate = useNavigate();
  const { token } = theme.useToken();
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const { userInfo, setUserInfo } = useModel('userModel');
  const { username = '', tempPassword = '', isRemember = false } = getCookie();

  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const data = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          ...data
        }));
      });
    }
  };

  const onFinish = async (values) => {
    const data = { ...values };
    const result = await request('/loginApi', { method: 'POST', data });
    const { code, msg } = result;
    if (code === 200) {
      //记住密码相关
      const { username, password, autoLogin } = values;
      if (autoLogin) {
        setCookie(username, password, 1);
      } else {
        clearCookie();
      }
      message.success('登录成功');
      localStorage.setItem('token', 'Bearer ' + msg);
      await fetchUserInfo();
      navigate('/home', { replace: true });
    }
  };

  return (
    <div className={styles.container}>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}>
        <LoginForm
          logo=""
          title="知思勤专利系统"
          subTitle="知思勤专利系统，一流的服务"
          initialValues={{
            username: username,
            password: tempPassword,
            autoLogin: isRemember,
          }}
          form={form}
          onFinish={onFinish}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />,
              }}
              placeholder={'用户名：'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'密码：'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
          <div
            style={{
              marginBlockEnd: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              记住密码
            </ProFormCheckbox>
            <a
              style={{ float: 'right' }}
              onClick={() => navigate('/register')}>
              免费注册</a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
